#!/usr/bin/env python

""" Example for analyse URIs for detect a Jboss attack 
    A detail explation of the attack is under http://www.deependresearch.org/ 
"""

__author__ = "Luis Campo Giralte"
__copyright__ = "Copyright (C) 2013-2020 by Luis Campo Giralte"
__revision__ = "$Id$"
__version__ = "0.1"

import sys
sys.path.append("../src/")
import pyaiengine

def callback_uri(flow):
    """ This callback is called on every http request to the server """
    uri = flow.http_info.uri
    if ((uri)and(len(uri) > 500)):
        """ A URI bigger than 500 bytes could be suspicious """
        items = uri.split("?")
        args = items[1].split("&")
        for arg in args:
            """ Iterate through the arguments """
            idx = arg.find("=")
            if (idx > -1):
                value = arg[idx + 1:]
                if (len(value) > 64):
                    """ Ummmm a value of an argument bigger than 64 """ 
                    decode = value.replace("%", "").decode("hex")
                    if (decode.find("Runtime.getRuntime().exec") > -1):
                        """ Somebody is executing remote commands """
                        print("[WARNING]: Jboss exploit detected")
                        print("[WARNING]: argument value:%s" % decode)

if __name__ == '__main__':

    stack = pyaiengine.StackLan()

    http_mng = pyaiengine.DomainNameManager()
    dom = pyaiengine.DomainName("My jboss host" ,"52.90.136.228:8080")
    re = pyaiengine.Regex("Set regex for Jboss uris", "^(/jmx-console/HtmlAdaptor).*")
    rm = pyaiengine.RegexManager()

    rm.add_regex(re)

    http_mng.add_domain_name(dom)
    dom.http_uri_regex_manager = rm 

    re.callback = callback_uri

    """ Plug the DomainNameManager on the HTTPProtocol """ 
    stack.set_domain_name_manager(http_mng,"HTTPProtocol")

    stack.tcp_flows = 50000
    stack.udp_flows = 16380

    with pyaiengine.PacketDispatcher("eth0") as pd:
        pd.stack = stack
        pd.run()

    sys.exit(0)

